<template>
  <div v-if="hub" class="box">
    <van-form @submit="onSubmit">
      <van-field
        readonly
        clickable
        name="picker"
        :value="value"
        label="镜像来源"
        placeholder="点击选择镜像来源"
        @click="showPicker = true"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>
      <van-field
        v-model.trim="imageName"
        type="text"
        name="imageName"
        label="镜像名称"
        placeholder="例如：nginx:1.7.8"
        style="margin-top: 10px"
        :rules="[{ required: true, message: '请填写镜像名称' }]"
      />
      <div class="tijiao">
        <van-button round block type="info" native-type="submit">
          拉取镜像
        </van-button>
      </div>
    </van-form>
  </div>
  <div v-else>
    <van-empty description="数据请求失败！" />
  </div>
</template>

<script>
import Vue from 'vue'
import { Base64 } from 'js-base64' // 编码插件
import { Form, Field, Button, Popup, Picker } from 'vant'

Vue.use(Form)
Vue.use(Field)
Vue.use(Button)
Vue.use(Popup)
Vue.use(Picker)
export default {
  data () {
    return {
      hub: null,
      imageName: '',
      value: 'HubDocker',
      columns: [],
      showPicker: false
    }
  },
  mounted () {
    this.fetchHub()
  },
  methods: {
    fetchHub () {
      const parse = {
        url: '/hubfind',
        method: 'GET'
      }
      this.$post(parse, res => {
        this.hub = res
        this.columns = this.hub.map(item => {
          return item.name
        })
        this.columns.unshift('HubDocker')
      })
    },
    onSubmit () {
      var name = this.imageName
      // 默认latest版本
      if (this.imageName.indexOf(':') === -1) {
        name = name + ':latest'
      }
      var parse = {}
      if (this.value === 'HubDocker') {
        parse = {
          data: {
            docker: `curl --unix-socket /var/run/docker.sock -s -X POST "http:/v1.40/images/create?fromImage=${name}"`
          }
        }
      } else {
        const arr = this.hub.filter(item => {
          return item.name === this.value
        })
        const myInfo = {
          serveraddress: arr[0].url,
          username: arr[0].username,
          password: Base64.decode(arr[0].password)
        }
        const token = Base64.encode(JSON.stringify(myInfo))
        parse = {
          data: {
            docker: `curl -s -X POST --unix-socket /var/run/docker.sock --header "X-Registry-Auth: ${token}" http:/v1.40/images/create?fromImage=${name}`
          }
        }
      }
      this.$post(parse, res => {
        this.$Notify({ type: 'success', message: '镜像拉取成功！' })
        this.$router.go(-1)
      })
    },
    onConfirm (value) {
      this.value = value
      this.showPicker = false
    }
  }
}
</script>

<style lang="scss" scoped>
.tijiao{
  margin: vw(30) auto;
  width: 50%;
}
</style>
